package com.wfx.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwt.util.JwtUtils;
import com.jwt.util.RsaUtils;
import com.wfx.entity.*;
import com.wfx.mapper.UserInfoMapper;
import com.wfx.mapper.WxbCustomerMapper;
import com.wfx.mapper.WxbMemeberMapper;
import com.wfx.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2021-01-20
 */

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxbCustomerMapper wxbCustomerMapper;
    @Autowired
    private WxbMemeberMapper wxbMemeberMapper;
    //查询
    @Override
    public PageResult<UserInfo> search(PageDTO<UserInfo> pageDTO) {
        if (pageDTO == null) {
            return new PageResult<UserInfo>(false,"查询失败",null,null,null);
        }
        IPage<UserInfo> iPage = new Page<>(pageDTO.getPage(),pageDTO.getLimit());
        UserInfo data = pageDTO.getData();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(pageDTO.getData());
        if (!StringUtils.isEmpty(data.getUserName())){
            queryWrapper.eq("user_name",data.getUserName());
        }
        IPage<UserInfo> pageInfo = userInfoMapper.selectPage(iPage, queryWrapper);
        PageResult pageResult = new PageResult<>();
        pageResult.setSuccess(true);
        pageResult.setData(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setMsg("查询成功");
        return pageResult;
    }
    //修改
    @Override
    public Result update(UserInfo userInfo) {
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userInfo.getUserId());
        int update = userInfoMapper.update(userInfo, updateWrapper);
        return new Result(update==1?true:false,update==1?"修改成功":"修改失败");
    }
    @Override
    public Result login(UserDto userDto) {

        if (userDto == null) {
            return new Result(false,"参数不合法");
        }

        if ("1".equals(userDto.getUserType())){//平台用户
            //根据用户名查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("account",userDto.getUsername());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            if (userInfo == null) {
                return new Result(false,"用户名或者密码不正确");
            }

            //比较密码（bcrypt）
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), userInfo.getPassword());
            if (matches != true) {//密码不正确
                return new Result(false,"用户名或者密码不正确");
            }
            //查询用户module信息
            UserInfo userInfo2 = userInfoMapper.findRoleByUser(userInfo);
            List<SysRole> userSysRole = userInfo2.getUserSysRole();
            UserInfo userInfo1 = userInfoMapper.findModulesByUser(userInfo);
            List<SysModule> modules = userInfo1.getUserModules();
            //查询用户role信息
            String moduleStr = "";
            String roleStr = "";
            for (SysModule module : modules) {
               moduleStr = moduleStr +","+module.getModuleName();
            }
            for (SysRole sysRole : userSysRole) {
                roleStr = sysRole.getRoleName()+","+roleStr;
            }
            //获取用户的角色和权限信息
            String joinStr = roleStr+moduleStr;
            userInfo.setRoleAndAuth(joinStr);
            //颁发令牌
            String token = genJwtToken(userInfo);
            if (token == null) {
                return new Result(false,"用户名或者密码不正确");
            }
            return new Result(true,"登录成功",token);
        }
        if("2".equals(userDto.getUserType())){//商户系统
            QueryWrapper<WxbMemeber> wrapper = new QueryWrapper<>();
            wrapper.eq("account",userDto.getUsername());
            WxbMemeber wxbMemeber = wxbMemeberMapper.selectOne(wrapper);
            if (wxbMemeber == null) {
                return new Result(false,"用户名或者密码不正确");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), wxbMemeber.getPassword());
            if (!matches) {//密码不正确
                return new Result(false,"用户名或者密码不正确");
            }


            //颁发令牌
            String token = genJwtToken(wxbMemeber);

            if (token == null) {
                return new Result(false,"用户名或者密码不正确");
            }


            return new Result(true,"登录成功",token);

        }



        if("3".equals(userDto.getUserType())){//自媒体系统

            QueryWrapper<WxbCustomer> wrapper = new QueryWrapper<>();
            wrapper.eq("login_name",userDto.getUsername());
            WxbCustomer customer = wxbCustomerMapper.selectOne(wrapper);



            if (customer == null) {
                return new Result(false,"用户名或者密码不正确");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), customer.getLoginPwd());
            if (!matches) {//密码不正确
                return new Result(false,"用户名或者密码不正确");
            }

            //颁发令牌
            String token = genJwtToken(customer);

            if (token == null) {
                return new Result(false,"用户名或者密码不正确");
            }


            return new Result(true,"登录成功",token);

        }

        return  new Result(false,"用户名或者密码不正确");

    }
    private  String  genJwtToken(Object userInfo){

        try {
            //从类路径中获取私钥
            String privateKeyPath = ResourceUtils.getFile("classpath:ras_private").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);

            String jwtToken = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);
            System.out.println(jwtToken);

            return jwtToken;

        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }


    }

}
